<template>
  <div class="bill-query-container">
    <h1>账单查询</h1>
    <div class="operation-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入账单ID或拨打用户搜索"
        style="width: 300px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>
    <el-table
      :data="formattedTableData"
      border
      style="width: 100%; margin-top: 15px;"
      v-loading="loading"
    >
      <!-- 账单ID（处理空值） -->
      <el-table-column prop="billId" label="账单ID" width="120">
        <template #default="scope">
          {{ scope.row.billId || '-' }}
        </template>
      </el-table-column>

      <!-- 用户名列 -->
      <el-table-column prop="userName" label="拨打用户" width="150">
        <template #default="scope">
          {{ scope.row.userName || '-' }} <!-- 处理空值，显示“-” -->
        </template>
      </el-table-column>

      <!-- 话费（确保数值显示正确） -->
      <el-table-column prop="bill" label="话费">
        <template #default="scope">
          ¥{{ (scope.row.bill || 0).toFixed(2) }}
        </template>
      </el-table-column>

      <!-- 计费状态 -->
      <el-table-column prop="status" label="计费状态">
        <template #default="scope">
          <span :class="scope.row.status === 1 ? 'success' : 'warning'">
            {{ scope.row.status === 1 ? '已计费' : '未计费' }}
          </span>
        </template>
      </el-table-column>

      <!-- 创建时间（处理空值和格式化） -->
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? formatDateTime(scope.row.createTime) : '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <div class="pagination-bar" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, computed } from 'vue';
import { getbillPageAPI } from '@/apis/bill';

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');
const loading = ref(false);

// 格式化表格数据（确保userName正确映射）
const formattedTableData = computed(() => {
  return tableData.value.map(item => ({
    billId: item.billId || item.bill_id || '',
    userName: item.userName || item.user_name || '-', // 映射用户名（优先userName，兼容user_name）
    bill: Number(item.bill) || 0,
    status: item.status || 0,
    createTime: item.createTime || item.create_time || null
  }));
});

// 初始化页面加载数据
onMounted(() => {
  fetchBillList();
});

// 时间格式化工具函数
const formatDateTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;

  return `${date.getFullYear()}-${
    (date.getMonth() + 1).toString().padStart(2, '0')
  }-${
    date.getDate().toString().padStart(2, '0')
  } ${
    date.getHours().toString().padStart(2, '0')
  }:${
    date.getMinutes().toString().padStart(2, '0')
  }:${
    date.getSeconds().toString().padStart(2, '0')
  }`;
};

// 获取列表数据
const fetchBillList = async () => {
  try {
    loading.value = true;
    const response = await getbillPageAPI(currentPage.value,searchKeyword.value == '' ? "***" :searchKeyword.value);
    console.log("账单接口返回数据:", response);

    if (response.code === 0) {
      const responseData = response.data || {};
      tableData.value = responseData.records || responseData || [];
      total.value = responseData.total || tableData.value.length;
      pageSize.value = responseData.size || 10;
    } else {
      ElMessage.warning('暂无账单数据');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取账单列表失败:', error);
    ElMessage.error('获取账单列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索功能
const handleSearch = async () => {
  console.log(searchKeyword.value);
  if (searchKeyword.value.trim() != '') {
    fetchBillList();
    return;
  }else{
    ElMessage.warning('请输入查询条件');
    return;
  }

  // try {
  //   loading.value = true;
  //   const response = await searchbillAPI(searchKeyword.value);
  //   if (response.code === 0) {
  //     tableData.value = response.data || [];
  //     total.value = tableData.value.length;
  //   } else {
  //     ElMessage.warning('未搜索到匹配账单');
  //     tableData.value = [];
  //     total.value = 0;
  //   }
  // } catch (error) {
  //   console.error('搜索账单失败:', error);
  //   ElMessage.error('搜索账单失败');
  // } finally {
  //   loading.value = false;
  // }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchBillList();
};

// 引入Element组件
const { proxy } = getCurrentInstance();
const ElMessage = proxy.$message;
</script>

<style lang="scss" scoped>
.bill-query-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.operation-bar {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.pagination-bar {
  margin-top: 15px;
  text-align: right;
}

.success {
  color: #10b981;
}

.warning {
  color: #f59e0b;
}
</style>
